package admin_api

import (
	"fmt"
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	"shop/admin/admin_service"
	"shop/entity"
	"shop/utils/convertutil"
	"shop/utils/result"
	"shop/utils/sessionutil"
	"shop/utils/tcentcloudutil"
)

func GetGoodsList(c *gin.Context) {
	result.RenderResult(c, admin_service.GetGoodsList(sessionutil.GetShopIdFromCtx(c)))
}

func AddGoods(c *gin.Context) {
	goods := new(entity.Goods)
	if err := c.ShouldBindJSON(goods); err != nil {
		result.RenderFail(c, "参数格式错误："+err.Error())
		return
	}

	result.RenderResult(c, admin_service.AddGoods(sessionutil.GetShopIdFromCtx(c), goods))
}

func UpdateGoods(c *gin.Context) {
	goods := new(entity.GoodsFilter)
	if err := c.ShouldBindJSON(goods); err != nil {
		result.RenderFail(c, "参数格式错误："+err.Error())
		return
	}

	goodsId := convertutil.ParseInt64(c.Param("id"))
	result.RenderResult(c, admin_service.UpdateGoods(goodsId, sessionutil.GetShopIdFromCtx(c), goods))
}

func UploadGoodsImg(ctx *gin.Context) {
	formFile, err := ctx.FormFile("file")
	if err != nil {
		seelog.Errorf("表单文件解析失败，err: %v, formFile: %v", err, formFile)
		result.RenderResult(ctx, result.Fail("文件解析失败"))
		return
	}

	file, err := formFile.Open()
	if err != nil {
		seelog.Errorf("文件打开失败，err: %v, formFile: %v", err, formFile)
		result.RenderResult(ctx, result.Fail("服务器异常：文件打开失败"))
		return
	}

	goodsId := convertutil.ParseInt(ctx.Param("id"))
	objKey := fmt.Sprintf("goodsImg/%d/%s", goodsId, formFile.Filename)
	url, err := tcentcloudutil.PutObject(objKey, file)
	if err != nil {
		result.RenderResult(ctx, result.Fail("图片上传失败: "+err.Error()))
		return
	}
	result.RenderResult(ctx, admin_service.UpdateGoodsImg(goodsId, url))
}

func DeleteGoods(c *gin.Context) {
	id := convertutil.ParseInt64(c.Param("id"))
	result.RenderResult(c, admin_service.DeleteGoods(id, sessionutil.GetShopIdFromCtx(c)))
}
